package com.baselib.libnetwork.net.callback;

import android.os.Environment;
import android.text.TextUtils;

import com.baselib.libnetwork.net.HttpManager;
import com.baselib.libnetwork.net.utils.HttpUtils;
import com.baselib.libnetwork.net.base.BaseCallback;
import com.baselib.libnetwork.net.base.Converter;
import com.baselib.libnetwork.net.utils.IOUtils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;

import okhttp3.Response;
import okhttp3.ResponseBody;

/**
 *
 */
public class FileConvert implements Converter<File> {

    public static final String DM_TARGET_FOLDER = File.separator + "download" + File.separator; //下载目标文件夹

    private String folder;                  //目标文件存储的文件夹路径
    private String fileName;                //目标文件存储的文件名
    private BaseCallback<File> callback;        //下载回调


    public FileConvert(String folder, String fileName) {
        this.folder = folder;
        this.fileName = fileName;
    }

    public void setCallback(BaseCallback<File> callback) {
        this.callback = callback;
    }

    @Override
    public File convertResponse(Response response) throws Exception {
        String url = response.request().url().toString();
        if (TextUtils.isEmpty(folder)) {
            folder = Environment.getExternalStorageDirectory() + DM_TARGET_FOLDER;
        }
        if (TextUtils.isEmpty(fileName)) {
            fileName = HttpUtils.getNetFileName(response, url);
        }

        File dir = new File(folder);
        IOUtils.createFolder(dir);
        File file = new File(dir, fileName);
        IOUtils.delFileOrFolder(file);

        InputStream bodyStream = null;
        byte[] buffer = new byte[8192];
        FileOutputStream fileOutputStream = null;
        try {
            ResponseBody body = response.body();
            if (body == null) {
                return null;
            }

            bodyStream = body.byteStream();
            long totalSize = body.contentLength();
            long currentSize = 0;
            int len;
            fileOutputStream = new FileOutputStream(file);
            while ((len = bodyStream.read(buffer)) != -1) {
                fileOutputStream.write(buffer, 0, len);

                if (callback == null) {
                    continue;
                }
                currentSize += len;
                onProgress(currentSize * 1.0f / totalSize);
            }
            fileOutputStream.flush();
            return file;
        } finally {
            IOUtils.closeQuietly(bodyStream);
            IOUtils.closeQuietly(fileOutputStream);
        }
    }

    private void onProgress(final float progress) {
        HttpManager.getInstance().getDelivery().post(new Runnable() {
            @Override
            public void run() {
                //进度回调的方法
                callback.onProgress(progress);
            }
        });
    }

}
